package controll;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.catalina.Manager;

import swimv2.entity.Request;
import swimv2.entity.Response;
import swimv2.entity.User;
import swimv2.session.ILoginRemote;
import swimv2.session.IWorkModuleRemote;
import utils.SCmd;
import utils.SeU;

/**
 * Servlet implementation class Message
 */
public class Message extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Message() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.process(response,request);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.process(response,request);
	}

	private void process(HttpServletResponse response,HttpServletRequest request) {
		
		HttpSession session = request.getSession();
		
		String next = "message.jsp";
		
		this.pulisciOutput(session,SeU.CONVERSATION_ATTRIBUTE);
		this.pulisciOutput(session,SeU.CONVERSATIONS_ATTRIBUTE);
		
		ILoginRemote log = (ILoginRemote)session.getAttribute(SeU.LOGIN_BEAN_ATTRIBUTE);
		if(log!=null)
		{
			//session.setAttribute(SeU.STATUS_ATTRIBUTE, "user");
			User u = (User)session.getAttribute(SeU.USER_ATTRIBUTE);
			
			String command = request.getParameter(SCmd.SERVLET_COMMAND);
			if(command!=null)
			{
				commandAnalisis(response, request, u, command);
			}
			else
			{
				prepareOutput(session, u, request);
				//DISPATCHER
				RequestDispatcher dispatcher = request
						.getRequestDispatcher(response.encodeURL(next));
				
				if (dispatcher!=null)
					try {
						dispatcher.forward(request, response);
					} catch (ServletException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		}
		else
		{
			try {
				response.sendRedirect(response.encodeURL("Home"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}

	private void pulisciOutput(HttpSession session,String s) {
		if(session.getAttribute(s)!=null)
		{
			session.removeAttribute(s);
		}
	}

	private void prepareOutput(HttpSession session, User u, HttpServletRequest request) {
		try {
			InitialContext ctx = new InitialContext();
			IWorkModuleRemote wm = (IWorkModuleRemote) ctx
					.lookup("IWorkModuleRemote");
			
			String s = request.getParameter(SeU.REQUEST_ATTRIBUTE_ID);
			
			List<Response> rl =wm.getConversations(u.getId());
			
			session.setAttribute(SeU.CONVERSATIONS_ATTRIBUTE, rl);
			
			if(request.getParameter(SeU.RESPONSE_ATTRIBUTE_ID) != null)
			{
				Integer id = Integer.parseInt(request.getParameter(SeU.RESPONSE_ATTRIBUTE_ID));
				List<swimv2.entity.Message> ms = wm.getMessageFromConversation(id);
				
				session.setAttribute(SeU.CONVERSATION_ATTRIBUTE, ms);
			}
			else if(request.getParameter(SeU.REQUEST_ATTRIBUTE_ID) != null)
			{
				Request rq = wm.getRequest(Integer.parseInt(request.getParameter(SeU.REQUEST_ATTRIBUTE_ID)));
				List<swimv2.entity.Message> ms = new ArrayList<swimv2.entity.Message>();
				
				ms.add(rq);
				session.setAttribute(SeU.CONVERSATION_ATTRIBUTE, ms);
			}
			else if(rl.size() != 0)
			{
				Integer id = rl.get(0).getId();
				List<swimv2.entity.Message> ms = wm.getMessageFromConversation(id);
				session.setAttribute(SeU.CONVERSATION_ATTRIBUTE, ms);
			}
			
			
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	private void commandAnalisis(HttpServletResponse response,HttpServletRequest request, User u, String command) {
		
		try {
			InitialContext ctx = new InitialContext();
			IWorkModuleRemote wm = (IWorkModuleRemote) ctx
					.lookup("IWorkModuleRemote");
			if (command.equals(SCmd.ADD_RESPONSE)) {
				
				Integer resp_id = null;
				if(request.getParameter(SeU.RESPONSE_ATTRIBUTE_ID)!=null)
				{
					resp_id = Integer.parseInt(request.getParameter(SeU.RESPONSE_ATTRIBUTE_ID));
				}

				Integer req_id = null;
				if(request.getParameter(SeU.REQUEST_ATTRIBUTE_ID)!=null)
				{
					req_id = Integer.parseInt(request.getParameter(SeU.REQUEST_ATTRIBUTE_ID));
				}
				
				wm.respond(u.getId(),
						request.getParameter(SeU.SUBJECT_ATTRIBUTE), 
						request.getParameter(SeU.TEXT_ATTRIBUTE), 
						req_id, 
						resp_id);
				
				response.sendRedirect("Message?"+SeU.RESPONSE_ATTRIBUTE_ID+"="+resp_id);
				
				
			} else if (command.equals(SCmd.CREATE_PUBLIC_REQUEST)) {

				wm.sendPublicRequest(u.getId(),
						request.getParameter(SeU.SUBJECT_ATTRIBUTE),
						request.getParameter(SeU.TEXT_ATTRIBUTE));

				response.sendRedirect(response.encodeURL("Home"));

			}
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
